package com.qq.clone.user.Service;

import com.qq.clone.commonAuth.Config.JwtUtils;
import com.qq.clone.user.Controller.VO.LoginRequestVO;
import com.qq.clone.user.Controller.VO.LoginResponseVO;
import com.qq.clone.user.Controller.VO.UserRegisterVO;
import com.qq.clone.user.Db.DO.UserDO;
import com.qq.clone.user.Db.Mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.OffsetDateTime;

@Service
public class UserServiceImp implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Mono<UserDO> register(UserRegisterVO vo) {
        if (vo.getUsername() == null || vo.getUsername().trim().isEmpty()) {
            return Mono.error(new Exception("用户名不能为空"));
        }
        if (vo.getPassword() == null || vo.getPassword().trim().isEmpty()) {
            return Mono.error(new Exception("密码不能为空"));
        }
        if (vo.getEmail() == null || vo.getEmail().trim().isEmpty()) {
            return Mono.error(new Exception("邮箱不能为空"));
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(vo, userDO);
        String encodedPassword = passwordEncoder.encode(vo.getPassword());
        userDO.setPassword(encodedPassword);
        userDO.setLastLogin(OffsetDateTime.now());
        userDO.setOnline(true);
        userMapper.insert(userDO);
        return Mono.just(userDO);
    }

    @Override
    public Mono<LoginResponseVO> login(LoginRequestVO reqVO) {
        String token = jwtUtils.generateToken(reqVO.getUsername(), reqVO.getUserId());
        return Mono.justOrEmpty(LoginResponseVO.builder()
                .token(token)
                .username(reqVO.getUsername())
                .userId(reqVO.getUserId())
                .build());
    }

    @Override
    public Mono<UserDO> getUserById(Long userId) {
        return Mono.justOrEmpty(userMapper.selectById(userId));
    }
}
